package com.cloudcc.mobile.dao.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import com.cloudcc.cloudframe.bus.BaseEvent;
import com.cloudcc.cloudframe.bus.DataEvent;
import com.cloudcc.cloudframe.bus.DynamicEventList.SendCommentEvent;
import com.cloudcc.cloudframe.bus.DynamicEventList.SendDynamicEvent;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList.DeleteCommentEvent;
import com.cloudcc.cloudframe.bus.EventList.DeleteDynamicEvent;
import com.cloudcc.cloudframe.bus.EventList.DynamicEvent;
import com.cloudcc.cloudframe.bus.EventList.DynamicSingleEvent;
import com.cloudcc.cloudframe.bus.EventList.FavotiteDynamicEvent;
import com.cloudcc.cloudframe.bus.EventList.LikeCommentEvent;
import com.cloudcc.cloudframe.bus.EventList.LikeDynamicEvent;
import com.cloudcc.cloudframe.bus.EventList.VoteDynamicEvent;
import com.cloudcc.cloudframe.model.DynamicModel;
import com.cloudcc.cloudframe.model.param.DynamicParam;
import com.cloudcc.cloudframe.model.param.FavoriteParam;
import com.cloudcc.cloudframe.model.param.LikeCommentParam;
import com.cloudcc.cloudframe.model.param.LikeDynamicParam;
import com.cloudcc.cloudframe.model.param.RemoveCommentParam;
import com.cloudcc.cloudframe.model.param.RemoveDynamicParam;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.IServer;
import com.cloudcc.cloudframe.net.async.AsyncClient;
import com.cloudcc.cloudframe.net.async.BeanRequest;
import com.cloudcc.cloudframe.net.async.EventRequest;
import com.cloudcc.cloudframe.net.async.GsonHttpResponseHandler;
import com.cloudcc.cloudframe.net.model.DynamicPopj;
import com.cloudcc.cloudframe.net.model.dynamic.PopjModelList.DeletePopj;
import com.cloudcc.cloudframe.net.model.dynamic.PopjModelList.FavoritePopj;
import com.cloudcc.cloudframe.net.model.dynamic.PopjModelList.LikePopj;
import com.cloudcc.cloudframe.net.model.dynamic.PopjModelList.SendCommentPopj;
import com.cloudcc.cloudframe.net.model.dynamic.PopjModelList.UploadBitmapPopj;
import com.cloudcc.cloudframe.net.model.dynamic.PopjModelList.VotePopj;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.dao.BaseEngine;
import com.cloudcc.mobile.dao.DynamicEngine;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.ManyImage;
import com.cloudcc.mobile.entity.VoteMicroPost;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostDMany;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostF;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostL;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostV;
import com.cloudcc.mobile.entity.chat.DraftBox;
import com.cloudcc.mobile.entity.comment.AddMicroComment;
import com.cloudcc.mobile.event.BeauEventList.DynamicListEvent;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.loopj.android.http.RequestParams;

public class DynamicEngineImpl extends BaseEngine implements DynamicEngine {


	/** * 获取我追随的内容 */
	@Override
	public String getMyChatter(String data) {
		String jsonString = "";
		try {
			String a = URLEncoder.encode(data, "utf-8");
			String url = UrlTools.url + UrlTools.url_path
					+ "serviceName=getMyChatter&data=" + a + "&binding="
					+ AppContext.binding;
			jsonString = NetWork.get(url.trim());
		} catch (Exception e) {
			Tools.handle(e);
		}
		return jsonString;
	}

	/** * 涉及我的更新，我所收藏的微贴， 所有微贴 */
	@Override
	public String getChatters(String data) {
		String jsonString = "";
		try {
			String a = URLEncoder.encode(data, "utf-8");
			String url = UrlTools.url + UrlTools.url_path
					+ "serviceName=getChatters&data=" + a + "&binding="
					+ AppContext.binding;
			jsonString = NetWork.get(url.trim());
		} catch (Exception e) {
			Tools.handle(e);
		}
		return jsonString;
	}

	/** * 获取我追随的内容 01 获取我追随 */
	@Override
	public String getMyChatter01(String data) {
		String jsonString = "";
		try {
			String a = URLEncoder.encode(data, "utf-8");
			String url = UrlManager.APP_UR + UrlTools.url_path
					+ "serviceName=getMyChatter01&data=" + a + "&binding="
					+ AppContext.binding;
			jsonString = NetWork.get(url.trim());
		} catch (Exception e) {
			Tools.handle(e);
		}
		return jsonString;
	}

	@Override
	public String getChatters01(String data) {
		String jsonString = "";
		try {
			String a = URLEncoder.encode(data, "utf-8");
			String url = UrlManager.getInterfaceUrl() + "?"
					+ "serviceName=getChatters01&data=" + a + "&binding="
					+ RunTimeManager.getInstance().getServerBinding();
			jsonString = NetWork.get(url.trim());
			LogUtils.d("net", "url:"+jsonString);
		} catch (Exception e) {
			Tools.handle(e);
		}
		return jsonString;
	}

	@Override
	public String voteMicroPost(String data) {
		String jsonString = "";
		try {
			String a = URLEncoder.encode(data, "utf-8");
			String url = UrlManager.APP_UR + UrlTools.url_path
					+ "serviceName=voteMicroPost&data=" + a + "&binding="
					+ AppContext.binding;
			jsonString = NetWork.get(url.trim());
		} catch (Exception e) {
			Tools.handle(e);
		}
		return jsonString;
	}

	@Override
	public void getDynamics(String serviceNmae, DynamicParam param,
			DynamicEvent event) {
		String json = GsonUtil.Object2Json(param);
		RequestParams params = new RequestParams();
		params.put("serviceName", serviceNmae);
		params.put("data", json);
		params.put("binding",RunTimeManager.getInstance().getServerBinding());
		AsyncClient.getInstance().get(UrlManager.getInterfaceUrl(),
				params,
				new GsonHttpResponseHandler<DynamicPopj>(DynamicPopj.class,
						event));

	}

	@Override
	public void FavoriteDynamic(FavoriteParam param, FavotiteDynamicEvent event) {
		String json = GsonUtil.Object2Json(param);
		RequestParams params = new RequestParams();
		params.put("serviceName", "favoriteFeed");
		params.put("data", json);
		params.put("binding", RunTimeManager.getInstance().getServerBinding());
		AsyncClient.getInstance().post(
				UrlManager.getInterfaceUrl(),
				params,
				new GsonHttpResponseHandler<FavoritePopj>(FavoritePopj.class,
						event));
	}

	@Override
	public void LikeDynamic(LikeDynamicParam param, LikeDynamicEvent event) {
		String json = GsonUtil.Object2Json(param);
		RequestParams params = new RequestParams();
		params.put("serviceName", "praiseFeed");
		params.put("data", json);
		params.put("binding", RunTimeManager.getInstance().getServerBinding());
		AsyncClient.getInstance().post(UrlManager.getInterfaceUrl(), params,
				new GsonHttpResponseHandler<LikePopj>(LikePopj.class, event));
	}

	@Override
	public void deleteDynamic(RemoveDynamicParam param, DeleteDynamicEvent event) {
		String json = GsonUtil.Object2Json(param);
		RequestParams params = new RequestParams();
		params.put("serviceName", "removeMicroPost");
		params.put("data", json);
		params.put("binding", RunTimeManager.getInstance().getServerBinding());
		AsyncClient.getInstance()
				.post(UrlManager.getInterfaceUrl(),
						params,
						new GsonHttpResponseHandler<DeletePopj>(
								DeletePopj.class, event));
	}

	@Override
	public void LikeComment(LikeCommentParam param, LikeCommentEvent event) {
		String json = GsonUtil.Object2Json(param);
		RequestParams params = new RequestParams();
		params.put("serviceName", "praiseComment");
		params.put("data", json);
		params.put("binding", RunTimeManager.getInstance().getServerBinding());
		AsyncClient.getInstance().post(UrlManager.getInterfaceUrl(), params,
				new GsonHttpResponseHandler<LikePopj>(LikePopj.class, event));
	}

	@Override
	public void deleteComment(RemoveCommentParam param, DeleteCommentEvent event) {
		sendPost(UrlManager.getInterfaceUrl(), DeletePopj.class, event, param,
				"removeMicroComment");
	}

	@Override
	public void getDynamic(DynamicParam param, DynamicSingleEvent event) {
		String json = GsonUtil.Object2Json(param);
		RequestParams params = new RequestParams();
		params.put("serviceName", "getChatters01");
		params.put("data", json);
		params.put("binding", RunTimeManager.getInstance().getServerBinding());
		AsyncClient.getInstance().post(
				UrlManager.getInterfaceUrl(),
				params,
				new GsonHttpResponseHandler<DynamicPopj>(DynamicPopj.class,
						event));
	}

	@Override
	public void sendComment(AddMicroComment param, SendCommentEvent event) {
		sendPost(UrlManager.getInterfaceUrl(), SendCommentPopj.class, event,
				param, IServer.COMMENT_ADD);
	}

	@Override
	public <T> void sendDynamic(final T params, SendDynamicEvent event,
			String serviceName) {

		RequestParams paramss = new RequestParams();
		paramss.put("serviceName", serviceName);
		paramss.put("data", GsonUtil.Object2Json(params));
		paramss.put("binding", RunTimeManager.getInstance().getServerBinding());
		AsyncClient.getInstance().post(
				UrlManager.getInterfaceUrl(),
				paramss,
				new GsonHttpResponseHandler<SendCommentPopj>(
						SendCommentPopj.class, event) {
					@Override
					public void onLoginInvalid() {
						mEvent.setOk(false);
						mEvent.setMessage("登录失效 ，正在 执行自动登录");
						mEvent.setStatusCode(BaseEvent.SC_LOGIN_INVAILED);
						EventEngine.post(mEvent);
					}

					@Override
					public void onFailure(ErrorInfo error) {
						// 发布微贴失败 保存到 数据库
						if (params instanceof AddMicroPostF) {
							saveWtF((AddMicroPostF) params);
						} else if (params instanceof AddMicroPostL) {
							saveWtL((AddMicroPostL) params);
						} else if (params instanceof AddMicroPostV) {
							saveWtV((AddMicroPostV) params);
						}
						mEvent.setOk(false);
						mEvent.setMessage(error.getErrorMessage());
						EventEngine.post(mEvent);
					}
				});
	}

	@Override
	public void uploadPhoto(final List<AddImageInfo> images,
			final AddMicroPostDMany addMicroPostDMany,
			final SendDynamicEvent event) {
		final List<ManyImage> imglist = new ArrayList<ManyImage>();
		for (int i = 0; i < images.size(); i++) {
			File file = new File(images.get(i).getImagePath());
			if (!file.exists()) {// 如果存在 就放弃
				continue;
			}
			ManyImage image = new ManyImage();
			image.setImgName(images.get(i).getImagePath());
			image.setAddress("");
			image.setImgHeight("");
			image.setImgWidth("");
			image.setImgId("");
			image.setImgType("jpg");
			imglist.add(image);
		}

		final String[] imagepaths = new String[imglist.size()];

		for (int i = 0; i < images.size(); i++) {
			imagepaths[i] = images.get(i).getImagePath();
			ManyImage image = new ManyImage();
			image.setImgName(images.get(i).getImagePath());
			image.setAddress("");
			image.setImgHeight("");
			image.setImgWidth("");
			image.setImgId("");
			image.setImgType("jpg");
			imglist.add(image);
		}
		String paramImages = GsonUtil.Object2Json(imglist);
		String decode1 = paramImages.replaceAll(" ", "%20");
		String decode = decode1;
		try {
			decode = URLEncoder.encode(decode1, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		RequestParams params = new RequestParams();

		for (int i = 0; i < imagepaths.length; i++) {
			try {
				File file = new File(imagepaths[i]);
				params.put("file" + (i + 1), file, file.getName());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

		String host = StringUtils.replace(UrlManager.getInterfaceUrl(),
				"https://", "http://");

		final String url = host + "?serviceName=uploadImgMany&data=" + decode
				+ "&binding=" + RunTimeManager.getInstance().getServerBinding();

		AsyncClient.getInstance().post(
				url,
				params,
				new GsonHttpResponseHandler<UploadBitmapPopj>(
						UploadBitmapPopj.class, null) {
					@Override
					public void onSuccess(UploadBitmapPopj t) {// 请求转换成
																// jsonbean成功
						// 发布 微贴
						String[] imageIds = t.data.imgId;
						if (imageIds == null || imageIds.length == 0) {
							onFailure(new ErrorInfo(101, "上传图片失败"));
						}
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < imageIds.length; i++) {
							sb.append(imageIds[i] + ",");
						}
						String a = sb.toString();
						addMicroPostDMany.setFileIds(a.substring(0,
								a.length() - 1));
						sendDynamic(addMicroPostDMany, event,
								"addMicroPostDMany");
					}

					@Override
					public void onFailure(ErrorInfo error) {
						saveWtP(addMicroPostDMany, images);
						event.setOk(false);
						event.setMessage(error.getErrorMessage());
						EventEngine.post(event);
					}

					@Override
					public void onLoginInvalid() {
						// 登录失效
						event.setOk(false);
						event.setMessage("登录失效 ，正在 执行自动登录");
						event.setStatusCode(BaseEvent.SC_LOGIN_INVAILED);
						EventEngine.post(event);
					}
				});

	}

	public boolean saveWtF(AddMicroPostF addMicroPostF) {
		DbUtils db = createDb();
		DraftBox box = createBox(db);
		box.setLeixing("addMicroPostF");
		addMicroPostF.setParent(box);
		box.setAddMicroPostF(addMicroPostF);
		try {
			db.saveBindingId(addMicroPostF);
			return true;
		} catch (DbException e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean saveWtL(AddMicroPostL addMicroPostL) {
		DbUtils db = createDb();
		DraftBox box = createBox(db);
		box.setLeixing("addMicroPostL");
		addMicroPostL.setParent(box);
		box.setAddMicroPostL(addMicroPostL);
		try {
			db.saveBindingId(addMicroPostL);
			return true;
		} catch (DbException e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean saveWtV(AddMicroPostV addMicroPostV) {
		DbUtils db = createDb();
		DraftBox box = createBox(db);
		box.setLeixing("addMicroPostV");
		addMicroPostV.setParent(box);
		box.setAddMicroPostV(addMicroPostV);
		try {
			db.saveBindingId(addMicroPostV);
			return true;
		} catch (DbException e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean saveWtP(AddMicroPostDMany addMicroPostDMany,
			List<AddImageInfo> list) {
		DbUtils db = createDb();
		DraftBox box = createBox(db);
		String pz = "";
		if (list.size() > 0) {
			pz = list.get(0).getImagePath();
			for (int i = 1; i < list.size(); i++) {
				pz = pz + "," + list.get(i).getImagePath();
			}
		}
		addMicroPostDMany.setList(pz);// 路径存在list里面
		box.setLeixing("addMicroPostDMany");
		addMicroPostDMany.setParent(box);
		box.setAddMicroPostDMany(addMicroPostDMany);
		try {
			db.saveBindingId(addMicroPostDMany);
			return true;
		} catch (DbException e) {
			e.printStackTrace();
			return false;
		}
	}

	private DbUtils createDb() {
		DbUtils db = DbUtils.create(AppContext.getInstance(), UserManager
				.getManager().getUser().userId + "box.db");
		return db;
	}

	private DraftBox createBox(DbUtils db) {
		DraftBox box = new DraftBox();
		box.setType("2");
		box.setTime(Tools.getTime(System.currentTimeMillis()));
		box.setIsNew("1");
		box.setClickable(true);
		return box;
	}

	@Override
	public void voteDynamic(VoteMicroPost param, VoteDynamicEvent event) {
		sendPost(UrlManager.getInterfaceUrl(), VotePopj.class, event, param, "voteMicroPost");
	}
	/**
	 * @deprecated 4.6.0.2版本之后建议少用bus总线 增强应用程序的可读性
	 */
	private <T> void sendPost(String url, Class<T> cclass, DataEvent<T> event,
			Object param, String serviceName) {
		String json = GsonUtil.Object2Json(param);
		RequestParams params = new RequestParams();
		params.put("serviceName", serviceName);
		params.put("data", json);
		params.put("binding", RunTimeManager.getInstance().getServerBinding());
		sendPost(url, params, cclass, event);
	}

	/**
	 * @deprecated use {@link #sendPost(String,RequestParams,BeanRequest)}
	 *             instead
	 */
	private <T> void sendPost(String url, RequestParams params, Class<T> cclass,
			DataEvent<T> event) {
		// 网络检测
		AsyncClient.getInstance().post(UrlManager.getInterfaceUrl(), params,
				new GsonHttpResponseHandler<T>(cclass, event));
	}

	@Override
	public void getDynamicsAboutRecord(DynamicParam param,
			DynamicListEvent event) {
		EventRequest<List<DynamicModel>> eventRequest = new EventRequest<List<DynamicModel>>(){};
		eventRequest.setEvent(event);
		sendPost(param, eventRequest, "getChatters01", true);
	}

}
